<?php
class UserHandler {
	public static function setUserVar($sVar, $mValue) {
		try {
			$oCheckQuery = DataHandler::query("
				SELECT id
				FROM users_vars
				WHERE user_id = ?
				AND varname = ?
			", $_SESSION['rid'], $sVar);

			if ($oCheckQuery->rowCount() > 0) {
				$oQuery = DataHandler::query("
					UPDATE users_vars
					SET varvalue = ?
					WHERE user_id = ?
					AND varname = ?
				", $mValue, $_SESSION['rid'], $sVar);
			}
			else {
				$oQuery = DataHandler::query("
					INSERT INTO users_vars (
						user_id,
						varname,
						varvalue
					) VALUES (
						?
						?
						?
					)
				", $_SESSION['rid'], $sVar, $mValue);
			}

			return true;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function delAttendance($iUser, $iTiming) {
		try {
		DataHandler::query("
			DELETE FROM attendance
			WHERE user_id = ?
			AND timing = ?
		", $iUser, $iTiming);
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function addAttendance($iUser, $iTiming, $sType) {
		$oQuery = DataHandler::query("
			INSERT INTO attendance (
				user_id,
				timing,
				type
			) VALUES (
				?,
				?,
				?
			)
		", $iUser, $iTiming, $sType);

		return DataHandler::lastInsertId();
		
	}
	
	public static function getAttendance($iUser) {
		try {
			if (is_array(@$GLOBALS['user_attendance'])) {
				return @$GLOBALS['user_attendance'];
			}

			$oQuery = DataHandler::query("
				SELECT
					type,
					timing
				FROM attendance
				WHERE user_id = ?
				ORDER BY timing DESC
			", $iUser);

			$GLOBALS['user_attendance'] = array();
			while (list($sType, $iTiming) = $oQuery->fetch()) {
				$GLOBALS['user_attendance'][] = array(
					'timing' => $iTiming,
					'type' => $sType
				);
			}
			
			return $GLOBALS['user_attendance'];
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function getUsergroups($iUser, $bForce = false)
	{
		try {
			if (is_array(@$GLOBALS['user_usergroups']) && !$bForce) {
				return $GLOBALS['user_usergroups'];
			}
			
			$oQuery = DataHandler::query("
				SELECT
					usergroup_id,
					access
				FROM users_groups
				WHERE user_id = ?
			", $iUser);

			$GLOBALS['user_usergroups'] = array();
			while (list($iUsergroup, $sAccess) = $oQuery->fetch())
			{
				$GLOBALS['user_usergroups'][$iUsergroup] = $sAccess;
			}
			return $GLOBALS['user_usergroups'];
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	/* To kill? 2011-12-26
	public static function getCommonJobAccess($iUser)
	{
		$mResult = UserDAO::getCommonJobAccess($iUser);
		if (is_array($mResult))
		{
			return $mResult;
		}

		switch ($mResult)
		{
			case -1:
				ErrorHandler::addError('SQL error');
				break;
			default:
				ErrorHandler::addError('Unknown error');
		}
	}
	*/
	
	public static function changeUser($iUser, $sUser, $sPass, $sPassAgain, $sFullname, $sEmail, $bAdmin, $bAccountant)
	{
		try {
			$oUsers = UserHandler::getUsers();
			if (!$oUsers[$_SESSION['rid']]->bAdmin && ($iUser != $_SESSION['rid'] || $bAdmin)) {
				throw new MiJobAccessException('Access denied');
			}

			if (!$sUser) {
				throw new MiJobException('User must have username');
			}

			if ($sPass != $sPassAgain) {
				throw new MiJobException('Passwords must match');
			}

			$oCheckQuery = DataHandler::query("
				SELECT id
				FROM ".DATA_USERBASE.".users
				WHERE user = ?
				AND id != ?
			", $sUser, $iUser);
			if ($oCheckQuery->rowCount() > 0) {
				throw new MiJobException('Username already taken');
			}

			if ($bAdmin) {
				$sLevel = 'admin';
			}
			else if ($bAccountant) {
				$sLevel = 'accountant';
			}
			else {
				$sLevel = 'user';
			}

			$oQuery = DataHandler::query("
				UPDATE users
				SET
					user = '$sUser',
					$sPassString
					name = '$sFullname',
					email = '$sEmail',
					level = '$sLevel'
				WHERE id = '$iUser'
			");

			if ($sPass) {
				$oPassQuery = DataHandler::query("
					UPDATE users
					SET pass = PASSWORD(?)
					WHERE id = ?
				", $sPass, $iUser);
			}
			return 1;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function delUser($iUser)
	{
		try {
			if ($iUser == $_SESSION['rid']) {
				throw new MiJobException('Can\' delete self');
			}

			$oUsers = UserHandler::getUsers();
			if (!$oUsers[$_SESSION['rid']]->bAdmin && $_SESSION['rid'] != $iUser) {
				throw new MiJobAccessException('Access denied');
			}

			$oUserQuery = DataHandler::query("
				DELETE FROM ".DATA_USERBASE.".users
				WHERE id = ?
			", $iUser);

			DataHandler::query("
				DELETE FROM users_groups
				WHERE user_id = ?
			", $iUser);

			DataHandler::query("
				UPDATE missionlog
				SET user_id = '0'
				WHERE user_id = ?
			", $iUser);

			DataHandler::query("
				UPDATE missions
				SET requester = '0'
				WHERE requester = ?
			", $iUser);

			DataHandler::query("
				UPDATE notes
				SET user_id = '0'
				WHERE user_id = ?
			", $iUser);

			DataHandler::query("
				UPDATE work
				SET user_id = '0'
				WHERE user_id = ?
			", $iUser);

			if (DATA_BASE != DATA_USERBASE) {
				DataHandler::query("
					DELETE FROM ".DATA_USERBASE.".apps_access
					WHERE user_id = ?
					AND app_name = '".cAppName."'
				", $iUser);
			}

			$oMissionCheckQuery = DataHandler::query("
				SELECT
					id,
					users
				FROM missions
				WHERE users LIKE ('%|?|%')
				OR users LIKE ('?|%')
				OR users LIKE ('%|?')
			", $iUser, $iUser, $iUser);
			while (list($iMission, $sUsers) = $oMissionCheckQuery->fetch())
			{
				$iUserArray = split('\|', trim($sUsers, '|'));
				$sNewUsers = "";
				for ($i = 0; $i < count($iUserArray); $i++)
				{
					if ($iUserArray[$i] != $iUser)
					{
						$sNewUsers .= $iUserArray[$i].'|';
					}
				}
				DataHandler::query("
					UPDATE missions
					SET users = ?
					WHERE id = ?
				", $sNewUsers, $iMission);
			}
			
			unset($GLOBALS['users']);
			
			return 1;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function addUser($sUser, $sPass, $sPassAgain, $sFullname, $sEmail, $bAdmin, $bAccountant)
	{
		try {
			$oUsers = UserHandler::getUsers();
			$oAppconfig = AppconfigHandler::getConfig();
			if (!$oUsers[$_SESSION['rid']]->bAdmin) {
				if ($oAppconfig['bAllowPublic']) {
					if ($bAdmin) {
						throw new MiJobAccessException("Access denied");
					}
				}
				else
				{
						throw new MiJobAccessException("Access denied");
				}
			}

			if (!$sUser) {
				throw new MiJobException("User must have a username");
			}

			if ($sPass != $sPassAgain) {
				throw new MiJobException("Passwords must match");
			}

			$oCheckQuery = DataHandler::query("
				SELECT id
				FROM users
				WHERE user = ?
			", $sUser);
			if ($oCheckQuery->rowCount() > 0) {
				throw new MiJobException("User already exists");
			}

			if ($bAdmin) {
				$sLevel = 'admin';
			}
			else if ($bAccountant) {
				$sLevel = 'accountant';
			}
			else {
				$sLevel = 'user';
			}
			$oQuery = DataHandler::query("
				INSERT INTO users (
					user,
					pass,
					name,
					email,
					level
				) VALUES (
					?,
					PASSWORD(?),
					?,
					?,
					?
				)
			", $sUser, $sPass, $sFullname, $sEmail, $sLevel);

			$iNewID = DataHandler::lastInsertId();

			unset($GLOBALS['users']);

			return $iNewID;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function getUsers() {
		if (DATABASE_OK !== true) {
			return array();
		}

		if (array_key_exists('users', $GLOBALS)) {
			return $GLOBALS['users'];
		}

		$oQuery = DataHandler::query("
			SELECT
				id,
				user,
				name,
				email,
				lastlogon,
				level
			FROM users
			ORDER BY user
		");

		$oUsers = array();
		while (list($iID, $sUser, $sFullname, $sEmail, $iLastlogon, $sLevel) = $oQuery->fetch())
		{
			$oUsers[$iID] = new User($iID, $sUser, $sFullname, $sEmail, ($sLevel == 'admin'), ($sLevel == 'admin' || $sLevel == 'accountant'), $iLastlogon);
		}

		$GLOBALS['users'] = $oUsers;
	
		return $oUsers;
	}
	
	public static function login($sUser, $sPass) {
		try {
			$oQuery = DataHandler::query('
				SELECT id
				FROM users
				WHERE user = ?
				AND pass = PASSWORD(?)
			', $sUser, $sPass);

			if ($oQuery->rowCount() == 0) {
				throw new MiJobException('Login failed');
			}

			$rowID = $oQuery->fetch();
			$iID = $rowID['id'];

			$oQuery = DataHandler::query('
				UPDATE users
				SET lastlogon = ?
				WHERE id = ?
			', thisSecond(), $iID);

			$oQuery = DataHandler::query('
				SELECT
					varname,
					varvalue
				FROM users_vars
				WHERE user_id = ?
			', $iID);

			while (list($sVar, $mValue) = $oQuery->fetch()) {
				$_SESSION['oUserVars'][$sVar] = $mValue;
			}

			return $iID;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	/* To kill? 2011-12-26
	public static function getCommonJobAccess($iUser)
	{
		// -1 = Unknown SQL error.
		$oUsergroups = UserHandler::getUsergroups($iUser);
		foreach ($oUsergroups as $iThisID => $oThisUsergroup)
		{
			$sExtraQuery .= "OR usergroup_id = '$iThisID'\n";
		}
		$oJobs = JobHandler::getJobs();
		$oQuery = doQuery("
			SELECT
				job_id,
				access
			FROM access
			WHERE user_id = '$iUser'
			$sExtraQuery
		");
		
		if (!$oQuery) {
			return -1;
		}
		
		$sJobAccess = array();
		while (list($iJob, $sAccess) = mysql_fetch_row($oQuery)) {
			if ($oJobs[$iJob]) {
				$sJobAccess[$iJob] = $sAccess;
			}
		}
		
		return $sJobAccess;
	}
	*/
}
?>
